package com.yanqu.road.server.manager.activity.yearMaster;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.yearMaster.YearMasterBoss;
import com.yanqu.road.entity.activity.yearMaster.YearMasterBossStateConfig;
import com.yanqu.road.entity.activity.yearMaster.YearMasterConfig;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.logic.activity.YearMasterLogic;
import com.yanqu.road.logic.bussiness.activity.YearMasterBussiness;
import com.yanqu.road.logic.cross.CrossActivityRankListModel;
import com.yanqu.road.logic.helper.ActivityHelper;
import com.yanqu.road.logic.pb.YearMasterPb;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.pb.yearMaster.YearMasterProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.activity.ActivityRankMgr;
import com.yanqu.road.server.protocol.GameProtocol;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class YearMasterActivity {


    //boss状态配置
    private Map<Integer, YearMasterBossStateConfig> yearMasterStateMap = new ConcurrentHashMap<>();

    //boss等级血量配置 等级从1级开始
    private Map<Integer, YearMasterConfig> yearMasterConfigMap = new ConcurrentHashMap<>();

    //活动id boss活动数据
    private YearMasterBoss yearMasterBoss;

    //活动基本数据
    private ActivityInfo activityInfo;

    //状态对应血量
    private Map<Integer, Long> stateHpMap;


    public YearMasterActivity(ActivityInfo ac) {
        initData(ac);
    }

    /**
     * 初始化数据
     *
     * @param activityInfo
     */
    private void initData(ActivityInfo activityInfo) {
        this.activityInfo = activityInfo;
        //加载boss血量配置
        yearMasterConfigMap = YearMasterBussiness.getYearMasterBossConfig(activityInfo.getActivityId());

        //param6 30;1;200|60;2;20|90;3;20|100;0;5|    <=血量百分比  格子类型  状态加成百分比    千分
        String param = activityInfo.getParam6();
        String[] stateConfigs = param.split("\\|");
        int index = 0;
        Map<Integer, YearMasterBossStateConfig> newConfigMap = new ConcurrentHashMap<>();
        for (String stateConfig : stateConfigs) {
            String[] config = stateConfig.split(";");
            YearMasterBossStateConfig cf = new YearMasterBossStateConfig();
            cf.setState(index++);
            cf.setBloodPercent(Integer.parseInt(config[0]));
            cf.setAdditionTypeId(Integer.parseInt(config[1]));
            cf.setAdditionPercent(Integer.parseInt(config[2]));
            newConfigMap.put(cf.getState(), cf);
        }
        yearMasterStateMap = newConfigMap;

        stateHpMap = YearMasterLogic.pareStateHpMap(yearMasterConfigMap, newConfigMap);
        //初始化boss数据
        initYearMasterBoss(activityInfo.getActivityId());
    }


    /**
     * 初始配置boss
     *
     * @return
     */
    private YearMasterBoss getConfigYearMasterBoss() {
        YearMasterConfig yearMasterConfig = getYearMasterConfigMap().get(1);
        YearMasterBoss info = new YearMasterBoss();
        info.setActivityId(yearMasterConfig.getActivityId());
        info.setCurrentBlood(0);
        info.setInsertOption();
        return info;
    }

    //根据配置初始化boss
    private YearMasterBoss initYearMasterBoss(int activityId) {
        synchronized (this) {
            if (yearMasterBoss == null) {
                YearMasterBoss bossData = YearMasterBussiness.getBossData(activityId);
                if (bossData != null) {
                    yearMasterBoss = bossData;
                } else {
                    yearMasterBoss = getConfigYearMasterBoss();
                }
            }
        }
        return yearMasterBoss;
    }


//------------------------------------------------------------boss--------------------------------------------------------------


    public void attackBoss(long userID, long score, int gridType, long serverId,int gridNum,int mode,String removeGrid) {
        ActivityInfo activityInfo = getActivityInfo();

        if (activityInfo == null || !ActivityHelper.activityInShowTime(activityInfo) || score <= 0) {
            return;
        }
        YearMasterBoss yearMasterBoss = getYearMasterBoss(activityInfo.getActivityId());

        boolean isChangeState = false;

        long addScore = score;
        //回包
        YearMasterProto.AttackBossFromCross.Builder result = YearMasterProto.AttackBossFromCross.newBuilder();
        result.setActivityId(activityInfo.getActivityId());
        result.setGridNum(gridNum);
        result.setGridType(gridType);
        result.setGameMode(mode);

        synchronized (this) {
            //根据当前boss状态获得喜庆值加成
            YearMasterBossStateConfig yearMasterState = getYearMasterSimpleState(yearMasterBoss);
            if (yearMasterState != null) {
                //0为所有类型都加
                if (yearMasterState.getAdditionTypeId() == gridType || yearMasterState.getAdditionTypeId() == 0) {
                    //千分
                    int additionPercent = yearMasterState.getAdditionPercent();
                    addScore = new BigDecimal(additionPercent).divide(BigDecimal.valueOf(1000)).add(BigDecimal.ONE)
                            .multiply(BigDecimal.valueOf(score)).setScale(0, BigDecimal.ROUND_UP).longValue();
                }
            }

            YearMasterStateDetail stateDetail = getStateDetail(yearMasterBoss.getCurrentBlood());
            //大于当前boss等级积分上限
            if (addScore + yearMasterBoss.getCurrentBlood() > stateDetail.getTotalBlood()) {
                YearMasterConfig nextYearMasterConfig = getYearMasterConfigMap().get(stateDetail.getLevel() + 1);
                if (nextYearMasterConfig == null) {
                    //积分改变
                    addScore = stateDetail.getTotalBlood() - yearMasterBoss.getCurrentBlood();
                    //最高等级
                    yearMasterBoss.setCurrentBlood(stateDetail.getTotalBlood());
                } else {
                    yearMasterBoss.setCurrentBlood(yearMasterBoss.getCurrentBlood() + addScore);
                }
            } else {
                yearMasterBoss.setCurrentBlood(yearMasterBoss.getCurrentBlood() + addScore);
            }


            YearMasterStateDetail resultStateDetail = getStateDetail(yearMasterBoss.getCurrentBlood());

            if (stateDetail.getState() != resultStateDetail.getState()) {
                isChangeState = true;
            }

            result.setBossInfo(YearMasterPb.parseBossInfo(getCopyYearBossInfo(yearMasterBoss)));
        }

        result.setRet(0);
        result.setAddScore((int) addScore);
        result.setRemoveGrid(removeGrid);
        int myRank = -1;
        CrossActivityRankListModel rankListModel = ActivityRankMgr.getCrossActivityNewRankListModel(activityInfo.getActivityId(), eGamePlayerEventType.YearMasterScoreCrossRank.getValue());
        if (rankListModel != null) {
            myRank = rankListModel.getMyRank(userID, serverId);
        }
        result.setMyRank(myRank);
        MessageHelper.sendPacket(serverId, userID, YanQuMessageUtils.buildMessage(GameProtocol.S_YEAR_MASTER_ATTACK_FROM_CROSS, result));


        //下发区服boss状态改变
        if (isChangeState) {
            syncActivityInfo();
        }

    }

    /**
     * 同步活动数据(状态变更时)
     */
    public void syncActivityInfo() {
        //获取boss数据
        YearMasterBoss simpleYearBossInfo = null;
        synchronized (this) {
            simpleYearBossInfo = getCopyYearBossInfo(getYearMasterBoss(getActivityInfo().getActivityId()));
        }
        List<Long> serverIdList = getActivityInfo().getServerIdList();
        for (long sId : serverIdList) {
            YearMasterProto.YearMasterNotifyInfo.Builder notifyBossInfo = YearMasterProto.YearMasterNotifyInfo.newBuilder();
            notifyBossInfo.setActivityId(getActivityInfo().getActivityId());
            if (simpleYearBossInfo != null) {
                notifyBossInfo.setBossInfo(YearMasterPb.parseBossInfo(simpleYearBossInfo));
            }
            MessageHelper.sendPacket(sId, 0, YanQuMessageUtils.buildMessage(GameProtocol.S_CROSS_ACTIVITY_YEAR_MASTER_BOSS_SYNC, notifyBossInfo));
        }
    }


    /**
     * 取当前喜庆值的等级 状态
     *
     * @param hp
     * @return
     */
    private YearMasterStateDetail getStateDetail(long hp) {

        YearMasterStateDetail yearMasterStateInfo = new YearMasterStateDetail();

        //根据当前喜庆值获取等级  等级上限喜庆值  上一等级上限喜庆值
        YearMasterConfig currentConfig = null;
        YearMasterConfig lastConfig = null;
        for (int i = 1; i <= getYearMasterConfigMap().size(); i++) {
            YearMasterConfig yearMasterConfig = getYearMasterConfigMap().get(i);
            if (yearMasterConfig != null) {
                if (hp < yearMasterConfig.getHp()) {
                    currentConfig = yearMasterConfig;
                    break;
                } else {
                    lastConfig = yearMasterConfig;
                }
            }
        }

        // 当前配置已经到达最大  取上一个lastConfig配置数值
        if (lastConfig != null && currentConfig == null) {
            yearMasterStateInfo.setLevel(lastConfig.getLevel());
            yearMasterStateInfo.setTotalBlood(lastConfig.getHp());
            yearMasterStateInfo.setLastTotalBlood(getYearMasterConfigMap().get(lastConfig.getLevel()).getHp());
            // yearMasterStateInfo.setState((yearMasterStateInfo.getLevel())*yearMasterStateMap.size());
            yearMasterStateInfo.setState(stateHpMap.size());
            return yearMasterStateInfo;
        }

        //设置当前等级 和 等级上限喜庆值
        if (currentConfig != null) {
            yearMasterStateInfo.setLevel(currentConfig.getLevel());
            yearMasterStateInfo.setTotalBlood(currentConfig.getHp());
        }

        //设置上一级喜庆值上限
        if (lastConfig != null) {
            yearMasterStateInfo.setLastTotalBlood(lastConfig.getHp());
        }


        for (int i = 1; i <= stateHpMap.size(); i++) {
            Long result = stateHpMap.get(i);
            if (result != null && hp >= result) {
                yearMasterStateInfo.setState(i);
            } else {
                break;
            }
        }
        // 状态
//        for (int i = 0; i < yearMasterStateMap.size(); i++) {
//            YearMasterBossStateConfig currentState = yearMasterStateMap.get(i);
//            int bloodPercent = currentState.getBloodPercent();
//            long result = new BigDecimal(bloodPercent).divide(BigDecimal.valueOf(1000))
//                    .multiply(new BigDecimal(yearMasterStateInfo.getTotalBlood() - yearMasterStateInfo.getLastTotalBlood()))
//                    .setScale(0, BigDecimal.ROUND_UP).toBigInteger().longValue();
//
//            //是否到达下一阶段
//            if (hp - yearMasterStateInfo.getLastTotalBlood() < result) {
//                yearMasterStateInfo.setState((yearMasterStateInfo.getLevel() - 1) * yearMasterStateMap.size() + currentState.getState());
//                break;
//            }
//        }

        return yearMasterStateInfo;
    }


    /**
     * 获取年兽简单状态
     *
     * @param yearMasterDetail
     * @return
     */
    private YearMasterBossStateConfig getYearMasterSimpleState(YearMasterBoss yearMasterDetail) {
        YearMasterStateDetail stateDetail = getStateDetail(yearMasterDetail.getCurrentBlood());
        return yearMasterStateMap.get(stateDetail.getState() % yearMasterStateMap.size());
    }


    /**
     * 获取临时对象
     *
     * @param yearMasterBoss
     * @return
     */
    public YearMasterBoss getCopyYearBossInfo(YearMasterBoss yearMasterBoss) {
        YearMasterBoss simple = new YearMasterBoss();
        YearMasterStateDetail stateDetail = getStateDetail(yearMasterBoss.getCurrentBlood());
        simple.setBossLevel(stateDetail.getLevel());
        simple.setState(stateDetail.getState());
        simple.setActivityId(yearMasterBoss.getActivityId());
        simple.setTotalBlood(stateDetail.getTotalBlood());
        simple.setCurrentBlood(yearMasterBoss.getCurrentBlood());
        simple.setLastLvBlood(stateDetail.getLastTotalBlood());
        return simple;
    }


    public void save() {
        if (yearMasterBoss != null) {
            if (yearMasterBoss.isUpdateOption()) {
                YearMasterBussiness.updateBossData(yearMasterBoss);
            } else if (yearMasterBoss.isInsertOption()) {
                YearMasterBussiness.addBossData(yearMasterBoss);
            }
        }
    }

    public ActivityInfo getActivityInfo() {
        return activityInfo;
    }

    public void setActivityInfo(ActivityInfo activityInfo) {
        this.activityInfo = activityInfo;
    }

    public YearMasterBoss getYearMasterBoss(int activityId) {
        if (yearMasterBoss == null) {
            initYearMasterBoss(activityId);
        }
        return yearMasterBoss;
    }

    public void setYearMasterBoss(YearMasterBoss yearMasterBoss) {
        this.yearMasterBoss = yearMasterBoss;
    }


    public Map<Integer, YearMasterConfig> getYearMasterConfigMap() {
        return yearMasterConfigMap;
    }

    public void setYearMasterConfigMap(Map<Integer, YearMasterConfig> yearMasterConfigMap) {
        yearMasterConfigMap = yearMasterConfigMap;
    }
}
